const morgan = require('morgan');
const logger = require('../utils/logger');

// 自定义token，用于记录请求ID或时间戳
morgan.token('timestamp', () => new Date().toISOString());

// 自定义格式，记录详细信息
const httpFormat = ':timestamp :method :url :status :res[content-length] - :response-time ms';

// 创建morgan中间件实例
const httpLogger = morgan(httpFormat, {
  stream: {
    write: (message) => {
      // 去除末尾换行符
      const logMessage = message.replace(/\n$/, '');
      
      // 解析日志信息
      const parts = logMessage.split(' ');
      if (parts.length >= 7) {
        logger.info('HTTP Access Log', {
          timestamp: parts[0],
          method: parts[1],
          url: parts[2],
          code: parts[3],
          contentLength: parts[4],
          responseTime: parts[6]
        });
      } else {
        logger.info(`HTTP Access Log: ${logMessage}`);
      }
    }
  }
});

module.exports = httpLogger;